package org.example.intern.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.example.intern.entity.dto.res.FileResourceRes;
import org.example.intern.utils.FastDFSUtils;
import org.example.intern.utils.Rest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @author: world
 * @date: 2022/4/19 9:31
 * @description: 文件处理
 */
@Slf4j
@Api(tags = "文件上传")
@RestController
@RequestMapping("file")
public class FileController {

    @Autowired
    private FastDFSUtils fastDFSUtils;

    @CrossOrigin(origins = "http://localhost:9528", allowCredentials= "true")
    @ApiOperation("文件上传")
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public Rest<FileResourceRes> upload(
            @ApiParam(value = "上传的文件",required = true,type = "file")
            @RequestParam("file") MultipartFile file
    ) {
        if (file.isEmpty()) {
            return Rest.faild("上传失败，请选择文件");
        }
        String originalFilename = file.getOriginalFilename();
        String fileExtName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        if (!"pdf".equals(fileExtName)){
            return Rest.faild("上传类型不为pdf");
        }
        try {

            String filePath = fastDFSUtils.uploadFile(file.getInputStream(),fileExtName);
            FileResourceRes res = new FileResourceRes(filePath, FastDFSUtils.DOMIN_PATH + filePath);
//            System.out.println(FastDFSUtils.DOMIN_PATH + filePath);
            return Rest.success(res);
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        return Rest.faild("上传失败");
    }
}
